package vn.vietel.pms.web.action;

import java.io.Serializable;
import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Synchronized;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.web.Session;

import vn.vietel.pms.business.UserServiceImpl;
import vn.vietel.pms.entity.User;
import vn.vietel.pms.service.IAuthenticator;

@Scope(ScopeType.SESSION)
@Synchronized
@Name("authenticator")
public class AuthenticatorAction implements IAuthenticator, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@In(required = false)
	@Out(required = false)
	
	@DataModelSelection
	private User user;
	
	@In("#{userService}")
	private UserServiceImpl userService;

	@DataModel
	private List<User> users;

	@In
	private FacesMessages facesMessages;

	private boolean loggedIn;

	public boolean authenticate() {
		User candicateUser = userService.selectUserByUserName(user
				.getUsername(), user.getPassword());
		
		if (candicateUser == null) {
			facesMessages.add("Invalid User to login");
			return false;
		} else {
			user = candicateUser;
			
			users = userService.selectAll();
			loggedIn = true;
			facesMessages.add("Welcome, #{user.name}");
			return true;
		}
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserServiceImpl getUserService() {
		return userService;
	}

	public void setUserService(UserServiceImpl userService) {
		this.userService = userService;
	}

	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public boolean isLoggedIn() {
		return loggedIn;
	}

	public void setLoggedIn(boolean loggedIn) {
		this.loggedIn = loggedIn;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public void logout() {
		loggedIn = false;
		Session.instance().invalidate();
		
	}

	public void validateLogin() {
		if(!loggedIn){
			facesMessages.add("Login first");
		}
	}
	
	public void delete(){
		if(user !=null){
			users.remove(user);
			userService.delete(user);
			user = null;
		}
	}

}
